/*
 * 
 * Copyright (C) 2010 Wilfried Elmenreich, Anita Sobe 
 * This file is part of VideoNetwork.
 * 
 * VideoNetwork is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. 
 */
package simulation;

import java.util.Random;

/**
 * Based on Zipf generator by Kenneth J. Christensen
 * www.cse.usf.edu/~christen/tools/genzipf.c
 * 
 * f(k,s,N)= (1/k^s)/(sum_1^N(1/n^s)) k=rank s=skew N=number of elements
 * 
 * @author Anita
 * 
 */
public class ZipfGenerator {

	private static double c = 0;

	/**
	 * 
	 * @param alpha
	 * @param n
	 * @param rand
	 * @return a number >-1 if everything is fine
	 */
	public static int nextZipf(double alpha, int n, Random rand) {
		// Static first time flag
		int zipf_value = -1;
		double z; // Uniform random number (0 < z < 1)
		double sum_prob; // Sum of probabilities

		// Compute normalization constant on first call only
		for (int i = 1; i <= n; i++)
			c += (1.0 / Math.pow((double) i, alpha));

		c = 1.0 / c;

		// Pull a uniform random number (0 < z < 1)
		do {
			z = rand.nextDouble();
		} while ((z == 0) || (z == 1));

		// Map z to the value
		sum_prob = 0;
		for (int i = 1; i <= n; i++) {
			sum_prob = sum_prob + c / Math.pow((double) i, alpha);
			if (sum_prob >= z) {
				zipf_value = i;
				break;
			}
		}
		return zipf_value;

	}

}
